//
//  RegisterViewController.m
//  Article
//
//  Created by Haricot_cpc17 on 16/4/25.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "RegisterViewController.h"
#import "LCTabBarController.h"
//#import "RetrievePasswordViewController.h"
#import "AFNetworking.h"
//#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "EditorViewController.h"
#import "LoginViewController.h"
#import "JPUSHService.h"


@interface RegisterViewController ()

@property (nonatomic,strong)UITextField *phoneTextField;//手机号
@property (nonatomic,strong)UITextField *passwordTextField;//密码
@property (nonatomic,strong)UITextField *ReTextfiled;//验证码
@property (nonatomic,strong)UITextField *inviteTextField;//邀请码

@property(nonatomic,strong)UIView *backview;


@end

@implementation RegisterViewController{
    NSTimer *_time;
    int     j;
    UIWebView * webview;
    UIButton *_lookBtn;
    int _count;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createUI];
    self.view.backgroundColor = [UIColor whiteColor];
}

-(void)createUI{
    
    _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *106/667 + HEIGHT *0/667, WIDTH - WIDTH *40/375, HEIGHT *40/667)];
    _phoneTextField.secureTextEntry = YES;
    _phoneTextField.placeholder = @"请输入手机号";
    [_phoneTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_phoneTextField setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [_phoneTextField setBorderStyle:UITextBorderStyleNone];
    [self.view addSubview:_phoneTextField];
    _phoneTextField.borderStyle = UITextBorderStyleRoundedRect;
    _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTextField.secureTextEntry = NO;
    _phoneTextField.tag = 100;
    
    _passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *106/667 + HEIGHT *60/667, WIDTH - WIDTH *40/375, HEIGHT *40/667)];
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.placeholder = @"请输入密码";
    [_passwordTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordTextField setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [_passwordTextField setBorderStyle:UITextBorderStyleNone];
    [self.view addSubview:_passwordTextField];
    _passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.tag = 101;
    
    _lookBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - WIDTH *60/375,HEIGHT *100/667 + HEIGHT *60/667, 40, 40)];
    [_lookBtn setImage:[UIImage imageNamed:@"眼睛"] forState:UIControlStateNormal];
    [self.view addSubview:_lookBtn];
    [_lookBtn addTarget:self action:@selector(LookClick:) forControlEvents:UIControlEventTouchUpInside];
    _count = 1;
    
    //验证码
    _ReTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *106/667 + HEIGHT *120/667, WIDTH - WIDTH *260/375, HEIGHT *40/667)];
    _ReTextfiled.secureTextEntry = YES;
    _ReTextfiled.placeholder = @"请输入验证码";
    [_ReTextfiled setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_ReTextfiled];
    [_ReTextfiled setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_ReTextfiled setBorderStyle:UITextBorderStyleNone];
    _ReTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    _ReTextfiled.secureTextEntry = NO;
    _ReTextfiled.tag = 103;
    
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH * 160/375, HEIGHT *106/667 + HEIGHT *120/667, WIDTH - WIDTH *180/375, HEIGHT *40/667)];
    button.backgroundColor = UIColorFromRGB(MYColor);
    button.layer.cornerRadius = 5;
    button.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    [button setTitle:@"发送验证码" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(retextfied) forControlEvents:UIControlEventTouchUpInside];
    button.tag = 852;
    [self.view addSubview:button];
    
    //    _inviteTextField = [[UITextField alloc]initWithFrame:CGRectMake(WIDTH *20/375, HEIGHT *156/667 + HEIGHT *120/667, WIDTH - WIDTH *40/375, HEIGHT *40/667)];
    //    _inviteTextField.secureTextEntry = YES;
    //    _inviteTextField.placeholder = @"请输入邀请码";
    //    [_inviteTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    //    [_inviteTextField setValue:[UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH] forKeyPath:@"_placeholderLabel.font"];
    //    [_inviteTextField setBorderStyle:UITextBorderStyleNone];
    //    [self.view addSubview:_inviteTextField];
    //    _inviteTextField.borderStyle = UITextBorderStyleRoundedRect;
    //    _inviteTextField.secureTextEntry = NO;
    //    _inviteTextField.tag = 102;
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textFieldClick)];
    [self.view addGestureRecognizer:tap];
    
    
    // [self.view addSubview:_textField];
    //提交按钮
    UIButton *submitBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH *40/375, HEIGHT *342/667, WIDTH - WIDTH *80/375,30)];
    submitBtn.backgroundColor = UIColorFromRGB(MYColor);
    [submitBtn setTitle:@"注册" forState:UIControlStateNormal];
    submitBtn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    [self.view addSubview:submitBtn];
    [submitBtn addTarget:self action:@selector(registClick:) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.layer.cornerRadius = 5;
    
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH *40/375, HEIGHT *390/667, WIDTH - WIDTH *80/375, 30)];
    backBtn.backgroundColor = UIColorFromRGB(MYColor);
    [backBtn setTitle:@"返回登录" forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14 *MYWIDTH];
    [self.view addSubview:backBtn];
    backBtn.layer.cornerRadius = 5;
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)LookClick:(UIButton *)btn{
    _count++;
    if (_count % 2 == 0) {
        _passwordTextField.secureTextEntry = NO;
    }if (_count % 2 == 1) {
        _passwordTextField.secureTextEntry = YES;
    }
}
-(void)textFieldClick{
    UITextField *textField = [(UITextField *)self.view viewWithTag:100];
    [textField resignFirstResponder];
    
    UITextField *textField1 = [(UITextField *)self.view viewWithTag:101];
    [textField1 resignFirstResponder];
    
    UITextField *textFiele2 = [(UITextField *)self.view viewWithTag:102];
    [textFiele2 resignFirstResponder];
    
    UITextField *textField3 = [(UITextField *)self.view viewWithTag:103];
    [textField3 resignFirstResponder];
    
    UITextField *codetextFied = [(UITextField *)self.view viewWithTag:741];
    [codetextFied resignFirstResponder];
    
}
- (void)retextfied{
    
    j = 59;
    if (!((_phoneTextField.text.length == 11) && [[_phoneTextField.text substringToIndex:1] isEqualToString:@"1"])){
        
        [self.view makeToast:@"请输入正确的手机号" duration:1.0 position:CSToastPositionCenter];
        
        return;
    }
    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://wz.ijiaque.com/app/app/imgverify.html"]];
    
    if (_backview == nil) {
        _backview = [[UIView alloc]initWithFrame:CGRectMake(30, 160*MYHEIGHT, WIDTH-60, 180)];
        _backview.backgroundColor = UIColorFromRGB(0xefeff1);
        _backview.layer.cornerRadius = 8;
        [self.view addSubview:_backview];
        
        UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, WIDTH-60, 20)];
        titlelab.text = @"请填写验证码";
        
        titlelab.font = [UIFont systemFontOfSize:15];
        titlelab.textAlignment = NSTextAlignmentCenter;
        [_backview addSubview:titlelab];
        
        UIButton *resignbut = [[UIButton alloc]initWithFrame:CGRectMake(0, _backview.frame.size.height-40, WIDTH/2-20, 40)];
        [resignbut setTitle:@"取消" forState:UIControlStateNormal];
        [resignbut addTarget:self action:@selector(resignWindow) forControlEvents:UIControlEventTouchUpInside];
        resignbut.titleLabel.font = [UIFont systemFontOfSize:14];
        [resignbut setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        [_backview addSubview:resignbut];
        
        UIButton *returnbut = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH/2-30, _backview.frame.size.height-40, WIDTH/2-30, 40)];
        [returnbut setTitle:@"保存" forState:UIControlStateNormal];
        [returnbut addTarget:self action:@selector(getMessage) forControlEvents:UIControlEventTouchUpInside];
        returnbut.titleLabel.font = [UIFont systemFontOfSize:14];
        [returnbut setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        [_backview addSubview:returnbut];
        
        UILabel *xian = [[UILabel alloc]initWithFrame:CGRectMake(0, _backview.frame.size.height-41, WIDTH-60, 0.5)];
        xian.backgroundColor = UIColorFromRGB(0x666666);
        [_backview addSubview:xian];
        UILabel *xian1 = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2-30, _backview.frame.size.height-28, 0.5, 25)];
        xian1.backgroundColor = UIColorFromRGB(0x666666);
        [_backview addSubview:xian1];
        
        
        webview = [[UIWebView alloc]initWithFrame:CGRectMake((WIDTH-60)/2-99, 35, 198, 48)];
        
        webview.backgroundColor = [UIColor clearColor];
        [_backview addSubview:webview];
        //webview.delegate = self;
        [webview loadRequest:request];
        
        
        
        UITextField * codetextFied = [[UITextField alloc]initWithFrame:CGRectMake( (WIDTH-60)/2-120, 90, 240, 40)];
        codetextFied.tag = 741;
        codetextFied.borderStyle = UITextBorderStyleNone;
        codetextFied.font =[UIFont systemFontOfSize:15];
        codetextFied.placeholder = @"  请输入验证码";
        codetextFied.backgroundColor = [UIColor whiteColor];
        [_backview addSubview:codetextFied];
        
    }else{
        [webview loadRequest:request];
        
        _backview.hidden = NO ;
        
    }
    
    
    
}
- (void)resignWindow
{
    _backview.hidden = YES ;
}
- (void)getMessage{
    
    _backview.hidden = YES ;
    
    NSLog(@"获取验证码");
    NSString *url = POSTSMS_URL;
    
    UITextField *codetextFied = (id)[self.view viewWithTag:741];
    
    NSDictionary *dic1 = @{@"mobile":_phoneTextField.text,
                           @"img_verify":codetextFied.text};
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    
    [manager POST:url parameters:dic1 success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 0) {
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }else{
            UIButton *but = (id)[self.view viewWithTag:852];
            [but setTitle:@"已发送" forState:UIControlStateNormal];
            [but setBackgroundColor:[UIColor grayColor]];
            but.userInteractionEnabled = NO;
            _time = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timer:) userInfo:nil repeats:YES];
        }
        
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}
- (void)timer:(NSTimer *)tim{
    UIButton *but = (id)[self.view viewWithTag:852];
    j = j-1;
    if (j == 0) {
        j = 59;
        [but setTitle:@"验证码" forState:UIControlStateNormal];
        [but setBackgroundColor:UIColorFromRGB(MYColor)];
        but.userInteractionEnabled = YES;
        [_time invalidate];
        _time=nil;
        
    }else{
        
        NSString *str = [[NSString alloc]initWithFormat:@"%dS",j];
        [but setTitle:str forState:UIControlStateNormal];
        [but setBackgroundColor:[UIColor grayColor]];
    }
}
#pragma mark 用户+标签、别名
-(void)joinJPush:(NSString *)alias{
    //    NSLog(@"123");
    NSLog(@"%@",alias);
    //[JPUSHService setTags:tag alias:@"yong" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:];
    
    //[JPUSHService setTags:tag aliasInbackground:@"yong"];
    
    [JPUSHService setTags:nil alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags , iAlias);
    }];
}
-(void)registClick:(UIButton *)button{
    NSLog(@"注册");
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    if ([_phoneTextField.text isEqualToString:@""]) {
        alert.title = @"手机号不能为空!";
        alert.tag = 1;
        [alert show];
    }if ([_passwordTextField.text isEqualToString:@""] ) {
        alert.title = @"密码不能为空!";
        alert.tag = 2;
        [alert show];
    }if([_ReTextfiled.text isEqualToString:@""]){
        alert.title = @"验证码不能为空!";
        alert.tag = 3;
    }else{
        
        NSDictionary *dic = @{@"mobile":_phoneTextField.text,
                              @"password":_passwordTextField.text,
                              @"reg_verify":_ReTextfiled.text
                              //,
                              //@"img_verify":@"2fy63"
                              };
        NSLog(@"%@",dic);
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [manager POST:REGISTER_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
            if ([str isEqualToString:@"1"]) {
                
                NSDictionary *dic2 = [dic1 objectForKey:@"data"];
                NSDictionary *levelDic = [dic2 objectForKey:@"level"];
                NSLog(@"levelDic  %@",levelDic);
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
                [user synchronize];
                NSLog(@"user %@",user);
                NSLog(@"user_token %@",[user objectForKey:@"user_token"]);
                
                [self.view makeToast:@"注册成功" duration:0.5 position:CSToastPositionCenter];
                NSLog(@"%@",dic1[@"info"]);
                [self login];
                
                
            }else{
                
                [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
                NSLog(@"%@",dic1[@"info"]);
            }
        }
              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  //   [MBProgressHUD hideHUDForView:self.view animated:YES];
                  [self.view makeToast:@"注册失败!" duration:1.0 position:CSToastPositionCenter];
                  NSLog(@"%@",error.description);
                  
              }];
    }
    
    
}
-(void)login{
    NSString * username = _phoneTextField.text;
    NSString * password = _passwordTextField.text;
    NSDictionary *dic = @{@"mobile":_phoneTextField.text,
                          @"password":_passwordTextField.text};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:LOGIN_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
        if ([str isEqualToString:@"1"]) {
            NSDictionary *dic2 = [dic1 objectForKey:@"data"];
            NSDictionary *levelDic = [dic2 objectForKey:@"level"];
            NSLog(@"levelDic  %@",levelDic);
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            //登录成功后把用户名和密码存储到UserDefault
            [user setObject:username forKey:@"mobile"];
            [user setObject:password forKey:@"password"];
            [user setObject:[dic2 objectForKey:@"uid"] forKey:@"uid"];
            [user setObject:[dic2 objectForKey:@"nickname"] forKey:@"nickname"];
            [user setObject:[dic2 objectForKey:@"avatar256"] forKey:@"imageurl"];
            [user setObject:[dic2 objectForKey:@"user_token"] forKey:@"token"];
            [user setObject:[dic2 objectForKey:@"sex"] forKey:@"sex"];
            [user setObject:[dic2 objectForKey:@"agents_level"] forKey:@"agents_level"];
            [user setObject:[dic2 objectForKey:@"share_count"] forKey:@"share_count"];

            [user synchronize];
            [self joinJPush:[NSString stringWithFormat:@"%@",[dic2 objectForKey:@"uid"]]];
            LCTabBarController *LCTabVC = [[LCTabBarController alloc]init];
            [self presentViewController:LCTabVC animated:YES completion:nil];
            NSLog(@"内部登录成功");
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"内部登录失败");
    }];
    
}

-(void)backClick:(UIButton *)button{
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
